package com.decade.rabbitmq.simple;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Author: decade
 * @Description: 简单模式：消费者
 * @Date: 2021/1/22 15:21
 **/
public class ReceiveTest {
    public static void main(String[] args) throws IOException, TimeoutException {
        //连接工厂
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.64.140");
        f.setUsername("admin");
        f.setPassword("admin");
        //建立连接
        Connection c = f.newConnection();
        //建立信道
        Channel ch = c.createChannel();
        //声明队列,如果该队列已经创建过，则不会重复创建
        ch.queueDeclare("helloworld", false, false, false, null);
        System.out.println("等待接收数据");

        //收到信息后用来 处理消息的回调对象
        DeliverCallback callback = new DeliverCallback() {
            @Override
            public void handle(String s, Delivery message) throws IOException {
                String msg = new String(message.getBody(),"UTF-8");
                System.out.println("收到："+msg);
            }
        };

        //消费者取消时的回调对象
        CancelCallback cancel = new CancelCallback() {
            @Override
            public void handle(String s) throws IOException {

            }
        };
        System.out.println("post");
        /**
         * 从helloworld队列接收信息
         * 参数:
         * 1.对象
         * 2.ack模式 ：true-自动ack，false-手动ack
         * 3.处理消息的回调对象
         * 4.取消信息的回调对象
         * */
        ch.basicConsume("helloworld", true, callback, cancel);
    }
}
